# Basend on the implementation in Qtile's documentation, modified to be more compliant with the Xresources specifications
# See https://qutebrowser.org/doc/help/configuring.html under "Reading colors from Xresources"

import subprocess, re
from qutebrowser.api import message

def read_xresources():
    props = {}
    x = subprocess.run(['xrdb', '-query'], capture_output=True, check=True, text=True)
    lines = x.stdout.split('\n')
    for line in lines:
        prop, _, value = line.partition(':\t')
        props[prop] = value
    return props

xresources=read_xresources()

def query_xresources(prefix, name, default):
    prefix=prefix + "."
    try:
        return xresources[prefix+name]
    except:
        while len(prefix)>0 :
            try:
                return xresources["*"+prefix+name]
            except:
                prefix=prefix[1:]
        try:
            return xresources["*"+name]
        except:
            message.warning("Could not find " + name + " in Xresources, using default: " + default)
            return default

def xresources_get_color(prefix, name, default):
        return re.sub("/","",re.sub("rgb:","#",query_xresources(prefix, name, default)))
